﻿/*
*┌────────────────────────────────────────────────┐
*│　描    述：Utils                                                   
*│　作    者： (Jxw)                                             
*│　版    本：1.0     
*│　功能描述：                                          
*│　创建时间：2021/4/28 9:56:59                        
*└────────────────────────────────────────────────┘
*/

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace Utility
{
    public class Utils
    {

        /// <summary>
        /// 将PDF文件转base64位编码
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string PDFToBase64(string path)
        {
            string base64string = "";
            try
            {
                FileStream ReadPdf = new FileStream(path, FileMode.Open);
                long FileSize = ReadPdf.Length;
                byte[] buffer = new byte[(int)FileSize];
                ReadPdf.Read(buffer, 0, (int)ReadPdf.Length);
                ReadPdf.Close();
                base64string = Convert.ToBase64String(buffer);
            }
            catch (Exception ex)
            {
                LogUtility.Error("PDFToBase64", "将PDF文件转base64位编码失败,原因:" + ex.Message);
            }
            return base64string;
        }

        /// <summary>
        /// base64转pdf
        /// </summary>
        /// <param name="json"></param>
        public static Dictionary<string, string> Base64ToPdf(string json, string taskCode)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string path = "";//声明一个string类型的相对路径
            string filename = "";//声明一个string类型的文件名
            try
            {
                string folderPath = string.Format("{0}\\{1}", AppConfig.ECGFile, DateTime.Now.ToString("yyyy"));
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                string monthPath = string.Format("{0}\\{1}", folderPath, DateTime.Now.ToString("yyyyMM"));
                if (!Directory.Exists(monthPath))
                {
                    Directory.CreateDirectory(monthPath);
                }

                string filePath = string.Format("{0}\\{1}", monthPath, DateTime.Now.ToString("yyyyMMdd"));
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                if (string.IsNullOrEmpty(taskCode))
                {
                    path = filePath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
                    int lenght = AppConfig.ECGFile.Length + 1;
                    string b = path.Substring(lenght, path.Length - lenght);
                    filename = b.Replace("\\", "/");
                }
                else {
                    path = filePath + "\\" +taskCode+ ".pdf";
                    int lenght = AppConfig.ECGFile.Length + 1;
                    string b = path.Substring(lenght, path.Length - lenght);
                    filename = b.Replace("\\", "/");
                }

                dic.Add(filename, path);

                byte[] bt = Convert.FromBase64String(json);
                FileStream fs = new FileStream(path, FileMode.Create);//FileMode.Createw文件存在则覆盖，不存在则创建新文件
                //FileStream fs = new FileStream(path, FileMode.CreateNew);//FileMode.CreateNew指定操作系统应创建新文件
                fs.Write(bt, 0, bt.Length);
                fs.Close();
            }
            catch (Exception ex)
            {
                LogUtility.Error("Base64ToPdf", "base64转pdf失败,原因:" + ex.Message);
            }
            return dic;
        }


        #region base64转图片
        /// <summary>
        /// 图片上传 Base64解码
        /// </summary>
        /// <param name="dataURL">Base64数据</param>
        /// <param name="imgName">图片名字</param>
        /// <returns>返回一个相对路径</returns>
        public static Dictionary<string,string>  Base64ToImage(string dataURL, string missionId)
        {
            //LogUtility.Debug("Base64ToImage", dataURL);

            Dictionary<string, string> dic = new Dictionary<string, string>();
            string path = "";//声明一个string类型的相对路径
            string filename = "";//声明一个string类型的文件名

            String base64 = dataURL.Substring(dataURL.IndexOf(",") + 1);      //将‘，’以前的多余字符串删除
            Bitmap bitmap = null;//定义一个Bitmap对象，接收转换完成的图片

            try//会有异常抛出，try，catch一下
            {

                byte[] arr = Convert.FromBase64String(base64);//将纯净资源Base64转换成等效的8位无符号整形数组

                System.IO.MemoryStream ms = new System.IO.MemoryStream(arr);//转换成无法调整大小的MemoryStream对象
                bitmap = new System.Drawing.Bitmap(ms);//将MemoryStream对象转换成Bitmap对象

                string folderPath = string.Format("{0}\\{1}", AppConfig.ECGFile, DateTime.Now.ToString("yyyy"));
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                string monthPath = string.Format("{0}\\{1}", folderPath, DateTime.Now.ToString("yyyyMM"));
                if (!Directory.Exists(monthPath))
                {
                    Directory.CreateDirectory(monthPath);
                }

                string filePath = string.Format("{0}\\{1}", monthPath, DateTime.Now.ToString("yyyyMMdd"));
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                if (string.IsNullOrEmpty(missionId))
                {
                    path = filePath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";

                    int lenght=AppConfig.ECGFile.Length+1; 
                    string b=path.Substring(lenght, path.Length - lenght);
                    filename = b.Replace("\\", "/");
                    //filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
                }
                else {
                    path = filePath + "\\" + missionId + ".png";//生成任务的心电报告
                    int lenght = AppConfig.ECGFile.Length + 1;
                    string b = path.Substring(lenght, path.Length - lenght);
                    filename = b.Replace("\\", "/");
                    //filename = missionId + ".png";//生成任务的心电报告
                }
                dic.Add(filename, path);
                //path = filePath + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
                //filename = "Knowledge_" + imgName + ".jpg";//所要保存的相对路径及名字
                //string url = HttpRuntime.AppDomainAppPath.ToString();
                //string tmpRootDir = System.Web.HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); //获取程序根目录 
                //string imagesurl2 = tmpRootDir + path; //转换成绝对路径 
                //bitmap.Save(imagesurl2, System.Drawing.Imaging.ImageFormat.Jpeg);//保存到服务器路径
                //bitmap.Save(filePath + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                //bitmap.Save(filePath + ".gif", System.Drawing.Imaging.ImageFormat.Gif);
                bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                ms.Close();//关闭当前流，并释放所有与之关联的资源
                bitmap.Dispose();
            }
            catch (Exception ex)
            {
                LogUtility.Error("Base64ToImage", "base64转图片失败,原因:" + ex.Message);
            }
            return dic;//返回相对路径
        }
        #endregion

        #region 图片转base64
        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="path">图片路径</param><br>       
        /// <returns>返回一个base64字符串</returns>
        public static string ImageToBase64(string path)
        {
            path = "E:/vs 2015/newaqtcprj/WEB/UpFile/2018/12/20181229174708_7471722c425a2ec08fa513ddf4f8c76306d55fbb0fbd9d8.jpg";
            string base64str = "";

            //站点文件目录
            string fileDir = HttpContext.Current.Server.MapPath("/");
            string[] arrfileDir = fileDir.Split('\\');
            fileDir = arrfileDir[0] + "\\" + arrfileDir[1] + "\\" + arrfileDir[2];
            try
            {
                //读图片转为Base64String
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Path.Combine(fileDir, "WEB\\UpFile\\2018\\12\\20181229174708_7471722c425a2ec08fa513ddf4f8c76306d55fbb0fbd9d8.jpg"));
                //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(path);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                bmp.Dispose();
                base64str = Convert.ToBase64String(arr);
            }
            catch (Exception e)
            {
                string mss = e.Message;
            }
            return "data:image/jpg;base64," + base64str;
        }
        #endregion

    }
}
